#!/bin/bash
################################################################################
# Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The OpenAirInterface Software Alliance licenses this file to You under 
# the Apache License, Version 2.0  (the "License"); you may not use this file
# except in compliance with the License.  
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#-------------------------------------------------------------------------------
# For more information about the OpenAirInterface (OAI) Software Alliance:
#      contact@openairinterface.org
################################################################################

# file run_hss
# brief run script for HSS_REL14.
# author  Tien-Thinh NGUYEN
# company Eurecom
# email:  tien-thinh.nguyen@eurecom.fr 



################################
# include helper functions
################################
THIS_SCRIPT_PATH=$(dirname $(readlink -f $0))
source $THIS_SCRIPT_PATH/../build/tools/build_helper

set_openair_env 
cecho "OPENAIRCN_DIR   = $OPENAIRCN_DIR" $green

declare    g_hss_default_config_file="/usr/local/etc/oai/hss_rel14.json"
declare    g_hss_default_fqdn="hss.openair4G.eur"

function help()
{
  set_openair_env
  echo_error " "
  echo_error "Usage: run_hss [OPTION]..."
  echo_error "Run the HSS executable (experimental)."
  echo_error " "
  echo_error "Options:"
  echo_error "Mandatory arguments to long options are mandatory for short options too."
  echo_error "  -c, --config-file  filename     Config file to be used by HSS if you don't want to use the default one: $g_hss_default_config_file"
  echo_error "  -I, --install-hss-files         Install HSS config files (NOT RECOMMENDED. See gitlab tutorial, https://gitlab.eurecom.fr/oai/openairinterface5g/wikis/OpenAirUsage or DOCS/EPC_User_Guide.pdf )"
  echo_error "  -g, --gdb                       Run with GDB."
  echo_error "  -h, --help                      Print this help."
  echo_error "  -k, --kill                      Kill the running local HSS."
}


function main() 
{
  local -i run_gdb=0
  local -i export_db=0
  local -i import_db=0
  local -i var_check_install_hss_files=0
  local    hss_config_file=$g_hss_default_config_file
  local    exe_arguments=" "

  until [ -z "$1" ]
    do
    case "$1" in
      -c | --config-file)
        hss_config_file=$2
        echo "setting config file to: $hss_config_file"
        shift 2;
        ;;
      -I | --install-hss-files)
        echo "Install HSS files: .conf files."
        var_check_install_hss_files=1
        shift;
        ;;
      -g | --gdb)
        run_gdb=1
        echo "setting GDB flag to: $GDB"
        shift;
        ;;
      -h | --help)
        help
        exit 0
        ;;
      -k | --kill)
        $SUDO killall -q oai_hss
        shift 1;
        exit 0
        ;;
      *)   
        echo "Unknown option $1"
        help
        exit 0
        ;;
    esac
  done


  #####################################
  # Install config files
  #####################################
  if [ ! -d /usr/local/etc/oai/freeDiameter ]; then
    $SUDO mkdir -m 777 -p /usr/local/etc/oai
    $SUDO mkdir -m 777    /usr/local/etc/oai/freeDiameter
  fi
    
  if [ ! -f $hss_config_file ]; then 
    if [ $g_hss_default_config_file != $hss_config_file ]; then
      echo_fatal "Please provide -c|--config-file valid argument (\"$hss_config_file\" not a valid file)"
    fi
  fi
  
  if [ $var_check_install_hss_files -gt 0 ];then
  
    if [ ! -f /usr/local/etc/oai/hss_rel14.json ]; then
      $SUDO cp -upv $THIS_SCRIPT_PATH/../etc/hss_rel14.json    /usr/local/etc/oai
      echo_fatal "Please customize /usr/local/etc/oai/hss_rel14.json, after, please re-run run_hss -I"
    else
      if [  $THIS_SCRIPT_PATH/../etc/hss_rel14.json -nt  /usr/local/etc/oai/hss_rel14.json ]; then
        read -p "Do you want to update /usr/local/etc/oai/hss_rel14.json with $OPENAIRCN_DIR/etc/hss_rel14.json ? <y/N> " prompt
        if [[ $prompt =~ [yY](es)* ]]; then
          $SUDO cp -upv $THIS_SCRIPT_PATH/../etc/hss_rel14.json    /usr/local/etc/oai
          echo_fatal "Please customize /usr/local/etc/oai/hss_rel14.json, after, please re-run run_hss -I"
        fi
      fi
    fi 
  
    $SUDO cp -upv $THIS_SCRIPT_PATH/../etc/acl.conf    /usr/local/etc/oai/freeDiameter
    echo_warning "Be carefull /usr/local/etc/oai/freeDiameter/acl.conf has realm hardcoded, please check it and change it upon your needs"
    $SUDO cp -upv $THIS_SCRIPT_PATH/../etc/hss_rel14_fd.conf /usr/local/etc/oai/freeDiameter
    echo_warning "Be carefull /usr/local/etc/oai/hss_rel14_fd.conf has realm and freeDiameter identity hardcoded, please check them and change them upon your needs"
  
    $SUDO cp -upv $THIS_SCRIPT_PATH/../etc/hss_rel14.conf /usr/local/etc/oai
  
    # hardcoded HSS diameter ID 
    IP_ADDRESS=`getent hosts $g_hss_default_fqdn | cut -d ' ' -f1`
    if [ "a$IP_ADDRESS" == "a" ]; then
      echo "127.0.1.1        $g_hss_default_fqdn hss" | $SUDO tee -a  /etc/hosts
      echo_warning "Set HSS FQDN "$g_hss_default_fqdn" in /etc/hosts, please check it and change it upon your needs"
    else
      if [ "127.0.1.1"  != "$IP_ADDRESS" ]; then
        echo_warning "FQDN $g_hss_default_fqdn resolution is the following: $IP_ADDRESS (better to use 127.0.1.1)"
      fi
    fi

    # generate certificates if necessary
    #echo_warning "Generating HSS certificates using HSS FQDN $g_hss_default_fqdn, if you want to use an other"
    #echo_warning "FQDN, please modify acl.conf, hss_fd.conf, /etc/hosts consistently and then "
    #echo_warning "re-run $OPENAIRCN_DIR/scripts/check_hss_s6a_certificate /usr/local/etc/oai/freeDiameter YOUR_HSS_FQDN"
    #$SUDO $OPENAIRCN_DIR/scripts/check_hss_s6a_certificate /usr/local/etc/oai/freeDiameter $g_hss_default_fqdn
  
    #Create Diameter Certificates
    $OPENAIRCN_DIR/src/hss_rel14/bin/make_certs.sh hss openair4G.eur
    if [ $? -ne 0 ]; then
      echo_error "Diameter certificate creation failed"
      return 1
    else
      echo_success "Diameter certificate creation succeeded"
    fi  
  fi



  #update configuration file hss_rel14.json if necessary, based on hss_rel14.conf
  value="`cat /usr/local/etc/oai/hss_rel14.conf | cut -d "#" -f1 | grep 'cassandra_Server_IP' | tr -d " " | grep "="`"
  eval $value
  var_name="cassandra_Server_IP"
  Cassandra_Server_IP=${!var_name}
  echo $Cassandra_Server_IP
  $SUDO sed -i "s/"@cassandra_Server_IP@"/$Cassandra_Server_IP/g" /usr/local/etc/oai/hss_rel14.json
    
  exe_arguments=$exe_arguments" -j $hss_config_file"
  
  #Calculate the OPc value for each UE (User Equipment).
  oai_hss  `echo $exe_arguments` --onlyloadkey
  
  if [ $? -ne 0 ]; then
     echo_error "OPC calculation failed"
     return 1
  else
     echo_success "OPC calculation succeeded"
  fi
  
  #####################################
  # Running executable
  #####################################
  if [ $run_gdb -eq 0 ]; then 
    $SUDO hss  `echo $exe_arguments` 2>&1 
  else
    $SUDO touch      ~/.gdb_hss
    $SUDO chmod 777  ~/.gdb_hss
    $SUDO echo "file oai_hss" > ~/.gdb_hss
    $SUDO echo "set args $exe_arguments   " >> ~/.gdb_hss
    $SUDO echo "run"                        >> ~/.gdb_hss
    $SUDO cat ~/.gdb_hss
    $SUDO gdb -n -x ~/.gdb_hss 2>&1
  fi
}


main "$@"
